package com.demo.deal_service.util;

import com.sun.javafx.iio.ios.IosDescriptor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class IOUtil {

    /**
     * 将一个输入流拷贝多个
     *
     * @param inputStream 被拷贝输入流
     * @param cpyNum      拷贝数量
     * @return 拷贝的inputstream数组
     */
    public static InputStream[] copyInputStream(InputStream inputStream, int cpyNum) throws IOException {
        InputStream[] ret = new InputStream[cpyNum];
        ByteArrayOutputStream baos = null;

        try {
            //用字节数组输出流获取输入流的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            //IOE可能抛出
            while ((len = inputStream.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();//IOE可能抛出

            //将字节数组输出流中的
            for (int i = 0; i < cpyNum; i++) {
                ret[i] = new ByteArrayInputStream(baos.toByteArray());
            }
        } finally {
            //关闭临时开启的资源
            if (baos != null) {
                baos.close();//IOE可能抛出
            }
        }

        return ret;
    }
}
